package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
)

type ContractController struct {
}

func ContractRegister(group *gin.RouterGroup) {
	contract := &ContractController{}
	group.POST("/save", contract.Save)
	group.GET("/detail", contract.Detail)
}

func (con *ContractController) Save(c *gin.Context) {
	params := &dto.ContractSaveInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	contract := &dao.Contract{}
	tx.Model(&dao.Contract{}).Where("is_delete = 0 AND status = 0").First(contract)
	if contract.Id == 0 {
		contract = &dao.Contract{
			Address:   params.Address,
			Phone:     params.Phone,
			HomeTitle: params.HomeTitle,
			Tip:       params.Tip,
		}
		if err := contract.Save(c, tx); err != nil {
			middleware.ResponseError(c, 500, errors.New("操作失败"), true)
			return
		}
		middleware.ResponseSuccess(c, "操作成功", true)
		return
	}
	if err := tx.Model(&dao.Contract{}).Where("id = ?", contract.Id).Updates(&dao.Contract{
		Address:   params.Address,
		Phone:     params.Phone,
		HomeTitle: params.HomeTitle,
		Tip:       params.Tip,
		Mark:      params.Mark,
	}).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
	return
}

func (con *ContractController) Detail(c *gin.Context) {
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	contract := &dao.Contract{}
	(&dao.Contract{}).InitData(tx)
	if err := tx.Model(&dao.Contract{}).Where("is_delete = 0 AND status = 0").First(contract).Error; err != nil {
		fmt.Println(err)
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, contract, true)
}
